package com.wf.day_0617.test3;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author mpk
 * @since 2024/6/17 18:28:46
 */

/*3.使用Semaphore ：有三个线程 分别打印A B C 要求有序打印 并且循环10次*/
public class Demo {


    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(1, true);


        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    semaphore.acquire();
                    System.out.print("A");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }
            }

        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    semaphore.acquire();
                    System.out.print("B");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }
            }

        });

        Thread thread3 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    semaphore.acquire();
                    System.out.println("C");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }
            }


        });

        thread1.start();
        //睡一小会等A启动
        try {
            Thread.sleep(0, 100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //睡一小会等B启动
        thread2.start();
        try {
            Thread.sleep(0, 100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        thread3.start();


    }


}
